#include "interlock_general.h"
#include "cslock.h"

static CCrtSection *g_interlocked_lock = NULL;
long
InterlockedIncrement(
             long volatile *lpAddend)
{
	if (!g_interlocked_lock)
	{
		g_interlocked_lock = new CCrtSection;
	}
    CAutoLock<CCrtSection> lock(*g_interlocked_lock);
	long temp = ++(*lpAddend) ;
    return temp;
}



long
InterlockedDecrement(
            long volatile *lpAddend)
{
	if (!g_interlocked_lock)
	{
		g_interlocked_lock = new CCrtSection;
	}
    CAutoLock<CCrtSection> lock(*g_interlocked_lock);
	long temp = --(*lpAddend);
    return temp;
}


long
InterlockedExchange(
            long volatile *Target,
            long Value)
{
	if (!g_interlocked_lock)
	{
		g_interlocked_lock = new CCrtSection;
	}
	CAutoLock<CCrtSection> lock(*g_interlocked_lock);
    long result = *Target;
	*Target = Value;
    return result;
}

long
InterlockedCompareExchange(
               long volatile *Destination,
               long Exchange,
			   long Comperand)
{
	if (!g_interlocked_lock)
	{
		g_interlocked_lock = new CCrtSection;
	}
	CAutoLock<CCrtSection> lock(*g_interlocked_lock);
    long result = *Destination;
	if(Comperand == *Destination){
		*Destination = Exchange;
	}
    return result;
}

